﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Three.BookStore.LoginERP;
using Volo.Abp.Domain.Repositories;

namespace Three.BookStore.RBAC
{
    /// <summary>
    /// 角色管理实现类
    /// </summary>
    public class Roles : IRoles
    {
        private readonly IRepository<RoleModel> _roleRepository;

        public Roles(IRepository<RoleModel> roleRepository)
        {
            _roleRepository = roleRepository;
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        public async Task<int> CreateAsync(RoleModel role)
        {
            var result = await _roleRepository.InsertAsync(role);
            return result.Id;
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        public async Task<int> UpdateAsync(RoleModel role)
        {
            var existingRole = await _roleRepository.GetAsync(x => x.Id == role.Id);
            if (existingRole == null)
            {
                throw new Exception($"未找到ID为{role.Id}的角色");
            }

            existingRole.RoleName = role.RoleName;
            await _roleRepository.UpdateAsync(existingRole);
            return existingRole.Id;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        public async Task<int> DeleteAsync(int id)
        {
            await _roleRepository.DeleteAsync(x => x.Id == id);
            return id;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        public async Task<List<RoleModel>> GetListAsync()
        {
            try
            {
                System.Console.WriteLine("开始获取角色列表");
                var roles = await _roleRepository.GetListAsync();
                System.Console.WriteLine($"从数据库获取到 {roles.Count} 个角色");
                return roles;
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine($"获取角色列表时发生错误: {ex}");
                throw;
            }
        }
    }
}
